<template>
  <div i="data-table">
    <el-table
      v-loading="isLoading"
      element-loading-background="rgba(0, 0, 0, 0.08)"
      element-loading-text="数据获取中，请稍后..."
      element-loading-spinner="el-icon-loading"
      ref="table"
      :empty-text="emptyText"
      :data="tableData"
      :height="height"
      :max-height="maxHeight"
      :border="noBorder"
      :lazy="lazy"
      :size="size"
      :row-key="rowKey"
      :row-style="rowStyle"
      :tree-props="treeProps"
      :load="handleLoad"
      :show-summary="showSummary"
      :highlight-current-row="highlightCurrentRow"
      :summary-method="getSummaries"
      @selection-change="handleSelectionChange"
      @current-change="handleCurrentChange"
      @row-click="handleRowClick"
    >
    </el-table>
    <slot></slot>

    <div class="talec">
      <!-- <el-pagination
                class="pagination"
                v-if="showPage"
                background
                @current-change="changePage"
                :current-page.sync="page"
                :layout="layout"
                :total="total"
                :page-size="pageSize">
            </el-pagination> -->
      <el-pagination
        @size-change="changeCurrentPage"
        :page-sizes="[10, 20, 50, 100, 200]"
        class="pagination"
        v-if="showPage"
        background
        @current-change="changePage"
        :current-page.sync="page"
        :layout="layout"
        :total="total"
        :page-size.sync="pagesizes"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import util from "/@/util/util";

export default {
  name: "DataTable",
  props: {
    // 合计显示字段
    showSummaryData: {
      type: Array,
      default: () => [],
    },
    // 表格数据
    tableData: {
      type: Array,
      default: () => [],
    },
    tableColumn: {
      type: Object,
      default: () => ({}),
    },
    // 是否无边框
    noBorder: {
      type: Boolean,
      default: true,
    },
    // 是否开启展开行功能
    showExpand: {
      type: Boolean,
      default: false,
    },
    // Table 的高度
    height: {
      type: [Number, String],
      default: null,
    },
    // Table 的最大高度
    maxHeight: {
      type: [Number, String],
      default: null,
    },
    // 是否要高亮当前行
    highlightCurrentRow: {
      type: Boolean,
      default: false,
    },
    // 分页组件布局
    layout: {
      type: String,
      default: "total, prev, pager, next, jumper",
    },
    // 分页总数
    total: {
      type: Number,
      default: 0,
    },
    // 序号是否显示
    showIndex: {
      type: Boolean,
      default: false,
    },
    // 显示行的增加删除
    addRow: {
      type: Boolean,
      default: false,
    },
    // 序号列名
    indexLable: {
      type: String,
      default: "序号",
    },
    // 序号列宽
    indexWidth: {
      type: Number,
      default: 80,
    },
    // 显示分页
    showPage: {
      type: Boolean,
      default: false,
    },
    lazy: {
      type: Boolean,
      default: false,
    },
    size: {
      type: String,
      default: "mini",
    },
    rowKey: {
      type: String,
      default: "id",
    },
    rowStyle: {
      type: [Object, Function],
      default: () => ({}),
    },
    treeProps: {
      type: Object,
      default: () => ({ children: "children", hasChildren: "hasChildren" }),
    },
    // 每页条数
    pagesize: {
      type: Number,
      default: 10,
    },
    // 当前页数
    currentPage: {
      type: Number,
      default: 1,
    },
    // 是否显示多选
    showSelection: {
      type: Boolean,
      default: false,
    },
    // CheckBox 是否可以勾选
    selectable: {
      type: Function,
      default: () => true,
    },
    // 显示合计行
    showSummary: {
      type: Boolean,
      default: false,
    },
    //加载loading
    isLoading: {
      type: Boolean,
      default: false,
    },
    //  无数据是展示
    emptyText: {
      type: String,
      default: "暂无数据",
    },
  },
  data() {
    return {
      pagesizes: this.pageSize,
      page: this.currentPage,
    };
  },
  computed: {
    // 工具类
    util() {
      return util;
    },
    column() {
      return Object.entries(this.tableColumn)
        .map((item) =>
          Object.assign(
            { prop: item[0] },
            typeof item[1] === "string" ? { label: item[1] } : item[1]
          )
        )
        .sort((a, b) => (b.prop === "operation" ? -1 : 0));
    },
  },
  watch: {
    currentPage(newVal) {
      this.page = this.currentPage;
    },
  },
  methods: {
    // 合计计算
    getSummaries(param) {
      // console.log(param);
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (this.showSummaryData.indexOf(column.property) != -1) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return util.accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        }
      });
      return sums;
    },
    renderHeader(h, { column }) {
      // h即为cerateElement的简写，具体可看vue官方文档
      alert("msg");
      // return h(
      //   'div',
      //   [
      //     h('span', column.label),
      //     h('i', {
      //       class:'el-icon-location',
      //       style:'color:#409eff;margin-left:5px;'
      //     })
      //   ],
      // );
    },

    // getDateVal(){
    //     console.log(this.$refs.dateRef)
    // },
    // 改变页条数后
    changeCurrentPage(pagesizes) {
      this.pagesizes = pagesizes;
      this.$emit("changeCurrentPage", pagesizes, this.page);
    },
    // 改变页数后
    changePage(page) {
      this.page = page;
      this.$emit("changePage", page);
    },
    // 触发多选框后
    handleSelectionChange(val) {
      this.$emit("changeSelection", val);
    },
    handleCurrentChange(val) {
      this.$emit("changeCurrent", val);
    },
    handleRowClick(row, column, event) {
      this.$emit("rowClick", row, column, event);
    },
    handleLoad(tree, treeNode, resolve) {
      this.$emit("load", tree, treeNode, resolve);
    },
    replaceProp(obj, str, prehook) {
      if (prehook) {
        return prehook(
          obj[str.match(/[a-zA-Z0-9_]+(?=\})/)[0]],
          str.match(/[a-zA-Z0-9_]+(?=\})/)[0],
          obj
        );
      }
      return obj[str.match(/[a-zA-Z0-9_]+(?=\})/)[0]];
    },
    showPower(value = 0) {
      let permissions = JSON.parse(localStorage.getItem("permissions") || "{}");
      if (typeof value === "number") {
        if (value === 0) return false;
        return permissions[value] ? permissions[value].showMenu : false;
      } else {
        let allPass = Array.isArray(value)
          ? value
              .map((item) => item.permission || 0)
              .some((item) => (value > 0 ? permissions[item].showMenu : true))
          : false;
        return allPass;
      }
    },

    minma(e) {
      this.$emit("addRow", e);
    },
  },
};
</script>
